#!/usr/bin/env python
# -*- coding: utf-8 -*-
PROXY = False

import os
import sys
import re
import signal
import socket
import urllib2
import tempfile
import gobject

from KernelCheck import about
from KernelCheck.constants import *
from KernelCheck.KernelPageParser import KernelPageParser
from KernelCheck.KCDebug import KCDebug

APPVERSION = "1.2.5"

try:
    import gtk
    import gtk.glade
except:
    print >> sys.stderr, "Вам необходимо установить python bindings(python привязки) для GNOME"
    sys.exit(1)

# Try to import vte
try:
    import vte
except:
    error = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, 'Вам необходимо установить python bindings для libvte')
    error.run()
    sys.exit (1)

# Close the about window
def close(w, res):
    if res == gtk.RESPONSE_CLOSE:
        gtk.main_quit()

# Trap interrupting signals and exit safely
def signal_handler(signal, frame):
    print
    print
    print "Перехвачен сигнал. безопасно завершаемся."
    try:
        gtk.main_quit()
    except:
        sys.exit(1)
    print

signal.signal(signal.SIGHUP, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGQUIT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)


class KernelCheck:

    # Procedure for the network connection
    def net_test(self):
        print "\nTестируем интернет-соединение ..."
        try:
            internet = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            internet.connect(("www.google.com", 80))
            return True
        except socket.error:
            return False

    # Procedure to retrieve all needed information
    def kernelinfo(self):

        ## ==============================================================
        ## The following code has been heavily modified by deepspring.
        ##
        ## The new code uses an alternative method to gather kernel
        ## patch information from kernel.org's fragment pages.
        ##

        ## Base URL for all kernel links
        base_url = 'http://www.kernel.org'

        ## Make a new kernel page parser object
        KPParser = KernelPageParser()

        ## Make a new KCDebug object
        kcd = KCDebug(True)

        try:## ----------------------------------------------------------
            ## Get and parse stable fragment page

            ## init variables
            patch = ''          # Patch Version
            patch_url = ''      # Patch URL
            patch_releasedate = ''  # Patch Release Date


            try:
                ## Parse the fragment page feed
                KPParser.feed(urllib2.urlopen("http://kernel.org/pub/linux/kernel/v2.6/").read())

            except IOError, e:
                if hasattr(e, 'reason'):
                    ## Output error to terminal window if we have one open
                    print 'не удалось установить соединение с kernel.org.'
                    print 'Reason: ' + str(e.reason)
                    ## Just in case they don't. Throw an error box at the user as well
                    error = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, 'не удалось установить соединение с kernel.org. Reason: ' + str(e.reason))
                    error.connect("response", close)
                    error.run()
                    sys.exit(1)

                elif hasattr(e, 'code'):
                    ## Output error to terminal window if we have one open
                    print 'сервер Kernel.org  не смог обработать запрос.'
                    print 'Код ошибки: ' + str(e.code)
                    ## Just in case they don't. Throw an error box at the user as well
                    error = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, 'сервер Kernel.org  не смог обработать запрос. Код ошибки: ' + str(e.code))
                    error.connect("response", close)
                    error.run()
                    sys.exit(1)

            ## Close the KernelPageParser feed
            KPParser.close()
            
            ## Increment our progress bar
            self.progressbar.set_fraction(0.10)
            self.progressbar.set_text("Загрузка данных: 10%")
            while gtk.events_pending():
                gtk.main_iteration(False)

            ## Iterate through our list of raw links
            patch = KPParser.get_patch_pkg("patch")
            print "Patch:" + patch

            ## for debugging purposes
            kcd.add_debug_msg(__file__, 'patch', patch)


            ## Get the current stable kernels release version
            point = patch.split('.')
            point1 = point[0]
            point2 = point[1]
            point3 = point[2]

            ## Stable version number = x.x.x, where x is a number
            stable = point1+"."+point2+"."+point3

            ## for debugging purposes
            kcd.add_debug_msg(__file__, 'stable', stable)

            ## Create a link to the stable kernel version
            stable_url = "http://kernel.org/pub/linux/kernel/v2.6/linux-" + stable + ".tar.bz2"
            patch_url = "http://kernel.org/pub/linux/kernel/v2.6/patch-" + patch + ".bz2"

            ## for debugging purposes
            kcd.add_debug_msg(__file__, 'stable_url', stable_url)

            ## Increment our progress bar
            self.progressbar.set_fraction(0.25)
            self.progressbar.set_text("Загрузка информации: 25%")
            while gtk.events_pending():
                gtk.main_iteration(False)

        except AttributeError:
            error = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, 'Произошла неизвестная рошибка. Невозможно получить верную информацию с master.kernel.org. Пожалуйста сообщите об этом  KernelCheck Team ASAP.')
            error.connect("response", close)
            error.run()


        try:
            ## ----------------------------------------------------------
            ## Get and parse prepatch page

            ## Initialise our variables
            prepatch = ''       ## Prepatch Version
            prepatch_url = ''       ## Prepatch URL
            prepatch_releasedate = ''   ## Prepatch Release Date
            prepatch_flag = ''      ## Prepatch Flag (if a prepatch exists)


            try:
                ## Parse the kernel fragment page
                KPParser.feed(urllib2.urlopen("http://kernel.org/pub/linux/kernel/v2.6/testing/").read())

            except IOError, e:
                if hasattr(e, 'reason'):
                    ## Output error to terminal window if we have one open
                    print 'Не получилось установить соелинение с kernel.org.'
                    print 'Причина: ' + str(e.reason)
                    ## Just in case they don't. Throw an error box at the user as well
                    error = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, 'Не получилось установить соелинение с kernel.org. Причина: ' + str(e.reason))
                    error.connect("response", close)
                    error.run()
                    sys.exit(1)

                elif hasattr(e, 'code'):
                    ## Output error to terminal window if we have one open
                    print 'сервер Kernel.org  не смог обработать запрос.'
                    print 'код ошибки: ' + str(e.code)
                    ## Just in case they don't. Throw an error box at the user as well
                    error = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, 'сервер Kernel.org  не смог обработать запрос. Код ошибки: ' + str(e.code))
                    error.connect("response", close)
                    error.run()
                    sys.exit(1)


            ## Close the feed
            KPParser.close()
                
            ## Iterate through raw links
            prepatch = KPParser.get_patch_pkg("prepatch")

            ## for debugging purposes
            kcd.add_debug_msg(__file__, 'prepatch', prepatch)

            if prepatch != None:
                ## Prepatch version
                prepatch_url = "http://kernel.org/pub/linux/kernel/v2.6/testing/patch-" + prepatch + ".bz2"
                ## for debugging purposes
                kcd.add_debug_msg(__file__, 'prepatch_url', prepatch_url)
            else:
                prepatch = "None"
                prepatch_url = "http://www.kernel.org"
                prepatch_releasedate = "None"
                prepatch_flag = 1
                

            ## Increment our progress bar
            self.progressbar.set_fraction(0.50)
            self.progressbar.set_text("Загрузка информации: 50%")
            while gtk.events_pending():
                gtk.main_iteration(False)

        except AttributeError:
            error = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, 'Произошла неизвестная рошибка. Невозможно получить верную информацию с master.kernel.org. Пожалуйста сообщите об этом  KernelCheck Team ASAP.')
            error.connect("response", close)
            error.run()


        try:
        ##---Retrieval: Old Kernels
            print "Ишем все доступные ядра более старых версий "

            try:
                htmlFeed = urllib2.urlopen("http://kernel.org/pub/linux/kernel/v2.6/")

            except IOError, e:
                if hasattr(e, 'reason'):
                    ## Output error to terminal window if we have one open
                    print 'Failed to communicate with kernel.org.'
                    print 'Причина: ' + str(e.reason)
                    ## Just in case they don't. Throw an error box at the user as well
                    error = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, 'Failed to communicate with kernel.org. Reason: ' + str(e.reason))
                    error.connect("response", close)
                    error.run()
                    sys.exit(1)

                elif hasattr(e, 'code'):
                    ## Output error to terminal window if we have one open
                    print 'сервер Kernel.org  не смог обработать запрос.'
                    print 'код ошибки: ' + str(e.code)
                    ## Just in case they don't. Throw an error box at the user as well
                    error = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, 'сервер Kernel.org  не смог обработать запрос. Код ошибки: ' + str(e.code))
                    error.connect("response", close)
                    error.run()
                    sys.exit(1)


            old_contents = htmlFeed.read()
            old_temp = tempfile.mktemp()
            old_path = 'file://' + old_temp
            old_file = os.open(old_temp, os.O_CREAT | os.O_RDWR)
            os.write(old_file, old_contents)
            os.close(old_file)
            print "Страница успешно загружена"
            print

            ###---The parse process - stable
            # Retrieves information about stable patch
            htmlFeed = urllib2.urlopen(old_path)

            OldKernelList = re.searchhtmlLinks = re.findall('<a href="linux-(.*).tar.bz2">', htmlFeed.read())
            OldKernelLinks = []

            t=type        # shortcut
            to=t(OldKernelList)       # store type of object to be reversed
            if to in (t(''),t(())): n=list(OldKernelList)  # for tuples and strings construct list
            else: n=to(OldKernelList) # otherwise call copy-constructor
            n.reverse()   # now call the inplace method
            ReverseList = n and (to==t('') and ''.join(n) or to==t(()) and tuple(n) or n) or to()


            for i in ReverseList:
                x = 'http://kernel.org/pub/linux/kernel/v2.6/linux-' + i + '.tar.bz2'
                OldKernelLinks.append(x)

            os.remove(old_temp)

            ## Added for debugging purposes
            kcd.add_debug_msg(__file__, 'OldKernelList', OldKernelList)
            kcd.add_debug_msg(__file__, 'OldKernelLinks', OldKernelLinks)

            self.progressbar.set_fraction(1.0)
            self.progressbar.set_text("З: 100%")
            while gtk.events_pending():
                gtk.main_iteration(False)

        except AttributeError:
            error = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, 'Произошла неизвестная рошибка. Невозможно получить верную информацию с master.kernel.org. Пожалуйста сообщите об этом  KernelCheck Team ASAP.')
            error.connect("response", close)
            error.run()

        ###---Return data
        return patch_url, patch, stable, stable_url, OldKernelList, OldKernelLinks, prepatch, prepatch_url


    def checkrelease(self):
        try:

            ###---Retrieval: KernelCheck
            print "Кешируется баннер с kcheck.sf.net"
            htmlFeed = urllib2.urlopen("http://kcheck.sourceforge.net/pool/finger_banner2")
            kcheck_contents = htmlFeed.read()
            kcheck_temp = tempfile.mktemp()
            kcheck_path = 'file://' + kcheck_temp
            kcheck_file = os.open(kcheck_temp, os.O_CREAT | os.O_RDWR)
            os.write(kcheck_file, kcheck_contents)
            os.close(kcheck_file)
            print "Страница успешно загружена"
            print

        except urllib2.HTTPError:
            print "Ошибка: kcheck.sourceforge.net недоступен."
            print
            sys.exit(1)

        ### WILL NOT WORK WITH PROXY
        ###---The parse process -- version
        htmlFeed = urllib2.urlopen(kcheck_path)
        htmlLinks = re.searchhtmlLinks = re.search('(.*)', htmlFeed.read())
        kernelcheck_release = htmlLinks.group(1)
        kernelcheck_release = kernelcheck_release.split('=')
        kernelcheck_release = kernelcheck_release[1].split(']')
        kernelcheck_release = kernelcheck_release[0]
        kernelcheck_release = str(kernelcheck_release)
        split = kernelcheck_release.split('.')
        major = split[0]
        minor = split[1]
        revision = split[2]
        os.remove(kcheck_temp)

        return kernelcheck_release, major, minor, revision

    # Procedure to retrieve running kernel information
    def runninginfo(self):
        # Gets your running kernel info
        running_kernel = os.uname()
        running_kernel = running_kernel[2]

        # Gets the running kernel information without the revision
        try:
            running_kernel = running_kernel.split('-')
            running_kernel = running_kernel[0]
        except:
            pass

        return running_kernel

    # If the user wants a typical compilation, use this
    def typical(self, widget):
        self.MainWindow.set_current_page(6)
        self.MainWindow.set_page_complete(self.vbox4, True)

    # If the user wants a custom compilation, use this
    def custom(self, widget):
        self.MainWindow.set_current_page(3)
        self.MainWindow.set_page_complete(self.vbox4, True)

    # Close the about window
    def close_about(self, w, res):
        if res == gtk.RESPONSE_CLOSE:
            w.hide()

    # Open the about dialog box
    def about(self, widget):
        about.run()

    # Disable those patches that cannot be used
    def check_patches(self):
        if prepatch == "":
            self.radPrepatch.set_sensitive(False)
            print "эксперементальные препатчи недоступны"
        if patch == stable:
            self.radPatch.set_sensitive(False)
            print "нет доступных патчей на данный момент"
            self.radNoPatch.set_active(True)

    # Set the sensitivity of the combobox
    def oldKernel_toggled(self, widget):
        print "использованы настройки старого ядра"
        sensitivity = widget.get_active()
        self.cboOldKernel.set_sensitive(sensitivity)

        # Add all needed items to the combobox
        if not self.alreadyretrieved:
            for i in OldKernelList:
                if not self.alreadyretrieved:
                    self.cboOldKernel.remove_text(0)
                self.alreadyretrieved = True
                self.cboOldKernel.prepend_text(i)
            self.cboOldKernel.set_active(0)

    def __init__(self):

        # Check if there is an internet connection
        if self.net_test() or PROXY:
            print "Connection found."
        else:
            # ADD PROXY SUPPORT
            error = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, 'Вы не подключены к интернету. Если вы используете прокси-сервер, то установите переменную  PROXY равной True в файле main.py .')
            error.run()
            print "Соединение разорвано. Используется интернет-прокси?"
            sys.exit(1)

        # Get the Glade file and retrieve needed widgets
        self.widgets = gtk.glade.XML(KCHECK_UI + "kernelcheck.glade")
        self.MainWindow = self.widgets.get_widget("MainWindow")
        self.lblIntroduction = self.widgets.get_widget("lblIntroduction")
        self.lblRunningKernel = self.widgets.get_widget("lblRunningKernel")
        self.lblLatestKernel = self.widgets.get_widget("lblLatestKernel")
        self.lblLatestKernelPatch = self.widgets.get_widget("lblLatestKernelPatch")
        self.lblLatestPrepatch = self.widgets.get_widget("lblLatestPrepatch")
        self.lblLatestMMPatch = self.widgets.get_widget("lblLatestMMPatch")
        self.lblLatestZenPatchset = self.widgets.get_widget("lblLatestZenPatchset")
        self.lblKernelPatchRelease = self.widgets.get_widget("lblKernelPatchRelease")
        self.lblKernelPrepatchRelease = self.widgets.get_widget("lblKernelPrepatchRelease")
        self.lblRetriever = self.widgets.get_widget("lblRetriever")
        self.lblInformation = self.widgets.get_widget("lblInformation")
        self.lblMessage = self.widgets.get_widget("lblMessage")
        self.radPatch = self.widgets.get_widget("radPatch")
        self.radPrepatch = self.widgets.get_widget("radPrepatch")
        self.radNoPatch = self.widgets.get_widget("radNoPatch")
        self.radMMPatch = self.widgets.get_widget("radMMPatch")
        self.radOldKernel = self.widgets.get_widget("radOldKernel")
        self.chkConfigure = self.widgets.get_widget("chkConfigure")
        self.chkReconfigureX = self.widgets.get_widget("chkReconfigureX")
        self.chkNvidia = self.widgets.get_widget("chkNvidia")
        self.chkFglrx = self.widgets.get_widget("chkFglrx")
        self.chkALSA = self.widgets.get_widget("chkALSA")
        self.chkInstallPackage = self.widgets.get_widget("chkInstallPackage")
        self.chkCustom = self.widgets.get_widget("chkCustom")
        self.chkCleanup = self.widgets.get_widget("chkCleanup")
        self.chkOptimize = self.widgets.get_widget("chkOptimize")
        self.progressbar = self.widgets.get_widget("progressbar")
        self.cboOldKernel = self.widgets.get_widget("cboOldKernel")
        self.spnJobs = self.widgets.get_widget("spnJobs")
        self.vbox2 = self.widgets.get_widget("vbox2")
        self.vbox1 = self.widgets.get_widget("vbox1")
        self.vbox3 = self.widgets.get_widget("vbox3")
        self.vbox4 = self.widgets.get_widget("vbox4")
        self.vbox5 = self.widgets.get_widget("vbox5")
        self.vbox6 = self.widgets.get_widget("vbox6")
        self.btn_About = self.widgets.get_widget("btn_About")
        self.btnUpdate = self.widgets.get_widget("btnUpdate")
        self.radMMPatch.set_sensitive(False)


        # Define and connect the event dictionary
        signalDic = { "on_MainWindow_destroy" : self.destroy_window,
                      "on_MainWindow_close" : self.destroy_window,
                      "on_MainWindow_cancel" : self.destroy_window,
                      "on_MainWindow_apply" : self.build,
                      "on_radOldKernel_toggled" : self.oldKernel_toggled,
                      "on_btnGetKernelInfo_clicked" : self.get_data,
                      "on_btnTypical_clicked" : self.typical,
                      "on_btnCustom_clicked" : self.custom,
                      "on_btn_About_clicked" : self.about,
                      "on_btnUpdate_clicked" : self.updates,
                      "on_MainWindow_apply" : self.build }
        self.widgets.signal_autoconnect(signalDic)

        # Enable the forward button on the first page
        self.MainWindow.set_page_complete(self.lblIntroduction, True)

        # Needed so that a sub procedure is not run every time old kernel is selected
        self.alreadyretrieved = False

    # Procedure to retrieve the data
    def get_data(self, widget):

        # Edit the label
        self.lblRetriever.set_markup("<b>получение информации с http://www.kernel.org/</b>")

        # Globalize the following variables
        global stable, stable_url, patch, patch_url, OldKernelList, OldKernelLinks, prepatch, prepatch_url

        # Get the web data
        patch_url, patch, stable, stable_url, OldKernelList, OldKernelLinks, prepatch, prepatch_url = self.kernelinfo()

        # Get the local data
        running_kernel = self.runninginfo()

        # Check what patches are available
        self.check_patches()

        # Set labels and allow the user to go to the following pages
        self.lblRetriever.set_markup("<b>информация получена.</b>")
        self.lblInformation.set_markup("<b>Последняя доступная информация</b>")
        self.MainWindow.set_page_complete(self.vbox1, True)
        self.MainWindow.set_page_complete(self.vbox2, True)
        self.MainWindow.set_page_complete(self.vbox3, True)
        #self.MainWindow.set_page_complete(self.vbox4, True)
        self.MainWindow.set_page_complete(self.vbox5, True)
        self.MainWindow.set_page_complete(self.vbox6, True)


        # Update the last page every tenth of a second
        gobject.timeout_add(100, self.build, 1)

        # Data is put into labels
        self.lblRunningKernel.set_text("Работающее сейчас ядро: " + running_kernel)
        self.lblLatestKernel.set_text("Последнее доступное ядро: " + stable)
        self.lblLatestKernelPatch.set_text("Последние доступные патчи ядра : " + patch)
        self.lblLatestPrepatch.set_text("Последние доступные препатчи ядра: " + prepatch)

    # When the user wants to build the kernel, run this
    def build(self, widget):

        if self.radPatch.get_active() == True:
            patchtype = "Normal"
            source = stable
            source_url = stable_url
            call = patch
            call_url = patch_url
        elif self.radPrepatch.get_active() == True:
            patchtype = "Prepatch"
            source = stable
            source_url = stable_url
            call = prepatch
            call_url = prepatch_url
        elif self.radNoPatch.get_active() == True:
            patchtype = "None"
            source = stable
            source_url = stable_url
            call = stable
            call_url = patch_url
        elif self.radOldKernel.get_active() == True:
            patchtype = "Older Stable Kernel"
            source = self.cboOldKernel.get_active_text()
            source_url = OldKernelLinks[self.cboOldKernel.get_active()]
            call = self.cboOldKernel.get_active_text()
            call_url = OldKernelLinks[self.cboOldKernel.get_active()]

        # Put the data in an array
        data = [source, source_url, call, call_url, patchtype]

        # Get the state of the checkboxes
        reconfigure = self.chkReconfigureX
        config = self.chkConfigure
        nvidia = self.chkNvidia
        alsa = self.chkALSA
        fglrx = self.chkFglrx
        optimize = self.chkOptimize
        installpackage = self.chkInstallPackage
        custom = self.chkCustom
        cleanup = self.chkCleanup
        ccjobs = self.spnJobs.get_value_as_int()

        options_tuple = []
        options = [config, alsa, optimize, reconfigure, nvidia, fglrx, installpackage, custom, cleanup]
        for i in options:
            answer = i.get_active()
            if answer:
                string = i.get_label()
                options_tuple.append(string)
            data.append(answer)
        options_tuple.append('CPU Jobs: ' + str(ccjobs))
        data.append(ccjobs)
        options_string = '\n'.join(options_tuple)

        if options_tuple == []:
            options_string = "None"



        if widget == 1:
            self.lblMessage.set_markup("<b>Ядро для компиляции :</b> " + str(call) + \
            "\n\n<b>Включенные опциии:</b>\n" + str(options_string))
            return True
        else:
            data_contents = str(data)
            data_temp = sys.argv[1]
            data_file = os.open(data_temp, os.O_CREAT | os.O_RDWR)
            os.write(data_file, data_contents)
            os.close(data_file)

            gtk.main_quit()

    # Check for program updates
    def updates(self, widget):
        kernelcheck_release, major, minor, revision = self.checkrelease()

        # Parse running version
        version = APPVERSION
        split = version.split('.')
        running_major = split[0]
        running_minor = split[1]
        running_revision = split[2]

        if major > running_major:
            print "обнаружен новый релиз."
            update = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_YES_NO, 'Найдены обновления. Хотите ли вы их применить? KernelCheck будет  закрыт, чтобы сделать возможным их применение.')
            update.connect("response", self.close3)
            update.run()
        elif minor > running_minor:
            print "обнаружен новый релиз."
            update = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_YES_NO, 'Найдены обновления. Хотите ли вы их применить? KernelCheck будет  закрыт, чтобы сделать возможным их применение.')
            update.connect("response", self.close3)
            update.run()
        elif revision > running_revision:
            print "найдена новая ревизия."
            update = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_YES_NO, 'Найдены обновления. Хотите ли вы их применить? KernelCheck будет  закрыт, чтобы сделать возможным их применение.')
            update.connect("response", self.close3)
            update.run()
        else:
            os.chdir('/tmp/')
            os.system('wget http://kcheck.sourceforge.net/pool/patches/bugfix.list')
            b = open('/tmp/bugfix.list', 'r')
            f = open(KCHECK_PREFIX + 'fixed.list', 'r')
            buglist = []
            notfound = False
            for line2 in b:
                f = open(KCHECK_PREFIX + 'fixed.list', 'r')
                for line1 in f:
                    if line1 != line2:
                        notfound = True
                    # Why not just assign notfound to False in the first place?
                    #else:
                        #notfound = False
                        #break
                f.close()
                if notfound:
                    line2 = line2.split('\n')
                    buglist.append(line2[0])
            os.remove('/tmp/bugfix.list')

            if len(buglist) > 0:
                print "Найдено новое исправление."
                update = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_YES_NO, 'Найдены обновления. Хотите ли вы их применить? KernelCheck будет  закрыт, чтобы сделать возможным их применение.')
                update.connect("response", self.close4, buglist)
                update.run()
            else:
                update = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, 'нет доступных обновлений.')
                update.connect("response", self.close5)
                update.run()

    # Response events for no updates
    def close5(self, w, res):
        if res == gtk.RESPONSE_CLOSE:
            w.hide()

    # Response events for bugfix
    def close4(self, w, res, buglist):
        if res == gtk.RESPONSE_YES:
            w.hide()
            gtk.main_iteration()
            for i in buglist:
                os.system('wget http://kcheck.sourceforge.net/pool/patches/fix-'+i)
                os.system('bash fix-'+i)
                os.remove('fix-'+i)
        elif res == gtk.RESPONSE_NO:
            w.hide()

    # Response events for version updates
    def close3(self, w, res):
        if res == gtk.RESPONSE_YES:
            w.hide()
            gtk.main_iteration()
            os.chdir('/tmp')
            os.system('wget http://kcheck.sourceforge.net/pool/patches/updater.sh')
            os.system('bash updater.sh &')
        elif res == gtk.RESPONSE_NO:
            w.hide()


    # Destroy the window
    def destroy_window(self, widget):
        gtk.main_quit()


if __name__ == '__main__':
    KernelCheck()
    gtk.main()
else:
    print "Не запускайте таким образом программу в следующий раз!"
    print "Пожалуйста вызовите эту программу правильно:"
    print "\"$ sudo kernelcheck\""
    sys.exit(1)
